﻿using System;
using System.Windows.Forms;
using MSOffice.Outlook;

namespace OutlookDuplicateRemover
{
    public partial class OutlookFolderSelectForm : Form
    {
        private readonly MSOffice.Outlook.Application app = null;
        private readonly string path = null;

        public Folder Folder { get; private set; }

        public OutlookFolderSelectForm(MSOffice.Outlook.Application app)
        {
            this.app = app;
        }

        public OutlookFolderSelectForm(MSOffice.Outlook.Application app, string path) : this(app)
        {
            InitializeComponent();

            this.path = path;

            this.Load += OutlookFolderSelectForm_Load;
            bOK.Click += bOK_Click;
        }

        private void bOK_Click(object sender, EventArgs e)
        {
            Folder = (Folder)tvFolders.SelectedNode.Tag;
        }

        private void OutlookFolderSelectForm_Load(object sender, EventArgs e)
        {
            BuildTree(app.Folders, tvFolders.Nodes);

            SelectFolder(path);
        }

        private void SelectFolder(string path)
        {
            if (!String.IsNullOrEmpty(path))
            {
                TreeNode[] nodes = tvFolders.Nodes.Find(path, true);

                if (nodes.Length == 1)
                    tvFolders.SelectedNode = nodes[0];
                else if (nodes.Length > 1)
                    MessageBox.Show(String.Format("Найдено более одной папки '{0}'", path), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(String.Format("Папка '{0}' не найдена", path), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void BuildTree(ItemCollection<Folder> folders, TreeNodeCollection nodes)
        {
            for (int i = 1; i <= folders.Count; i++)
            {
                if (folders[i].DefaultItemType == ItemType.MailItem)
                {
                    Folder f = folders[i];

                    BuildTree(f.Folders, AddNode(nodes, f).Nodes);
                }
            }
        }

        private static TreeNode AddNode(TreeNodeCollection nodes, Folder f)
        {
            TreeNode newNode = nodes.Add(f.FullFolderPath, f.Name);

            newNode.Tag = f;

            return newNode;
        }

        public Folder GetFolder(string path)
        {
            tvFolders = new TreeView();

            BuildTree(app.Folders, tvFolders.Nodes);
            SelectFolder(path);

            return (Folder)tvFolders.SelectedNode.Tag;
        }
    }
}
